<?php
namespace app\admin\controller;

use app\common\validate\AdminUser;
use think\Controller;
use app\common\lib\IAuth;

class Login extends Base
{

    public function _initialize() {
    }
    public function index()
    {
        
            return $this->fetch();
    }

    /**
     * 登录相关业务
     */
    public function check() {
        if(request()->isPost()) {
            $data = input('post.');
            $validate=$this->validate($data,[
                'username|用户名'=>'require',
                'password|密码' => 'require',
                'code|验证码' => 'require'

            ]);
            if($validate !== true){
                $this->error($validate,'admin/login/index');

            }
            if (!captcha_check($data['code'])) {
                //验证码错误
                $this->error('验证码错误','admin/login/index');

            }
            try {
                // username  username+password
                $user = model('AdminUser')->get(['username' => $data['username']]);
            }catch (\Exception $e) {
                $this->error($e->getMessage());
            }



            // 再对密码进行校验
            if (IAuth::setPassword($data['password']) != $user['password']) {
                $this->error('密码不正确或用户不存在');
            }
            // 1 更新数据库 登录时间 登录ip
            $udata = [
                'last_login_time' => time(),
                'last_login_ip' => request()->ip(),
            ];

            try {
                model('AdminUser')->save($udata, ['id' => $user->id]);
            }catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            // 2 session
            session(config('admin.session_user'), $user, config('admin.session_user_scope'));
            $this->success('登录成功', 'index/index');

            //halt($user);
        }else {
            $this->error('请求不合法');
        }
    }



    /**
     * 退出登录的逻辑
     * 1、清空session
     * 2、 跳转到登录页面
     */
    public function logout() {
        session(null, config('admin.session_user_scope'));
        // 跳转
//        $this->redirect('login/index');
        $this->success('成功退出','login/index');
    }
    public function captcha()
    {
        //验证码标识
        $uniqid = uniqid(mt_rand(100000, 999999));
        //返回数据 验证码图片路径、验证码标识
        $data = [
            'src' => captcha_src($uniqid),
            'uniqid' => $uniqid
        ];
        $this->ok($data);
    }
}
